CODE 118. Roman to Integer

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/10/2013-11-10-CODE 118 Roman to Integer/

访问原文「CODE 118. Roman to Integer

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
static Map<Character, Integer> r2a = new HashMap<Character, Integer>();
static {
r2a.put('I', 1);
r2a.put('V', 5);
r2a.put('X', 10);
r2a.put('L', 50);
r2a.put('C', 100);
r2a.put('D', 500);
r2a.put('M', 1000);
}
public int romanToInt(String s) {
// Start typing your Java solution below
// DO NOT write main() function
char[] cs = s.toCharArray();
int num = 0;
int tmp = 0;
int tmpStep = -1;
for (char c : cs) {
int ttmp = r2a.get(c);
if (-1 == tmpStep) {
tmpStep = ttmp;
tmp = ttmp;
} else if (ttmp == tmpStep) {
tmp += ttmp;
} else if (ttmp > tmpStep) {
tmp = ttmp - tmp;
num += tmp;
tmp = 0;
tmpStep = -1;
} else if (ttmp < tmpStep) {
num += tmp;
tmpStep = ttmp;
tmp = ttmp;
}
}
num += tmp;
return num;
}
Jerky Lu wechat
欢迎加入微信公众号